package com.n4v1.pko.server.network.serverpackets;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

import com.n4v1.pko.server.model.actor.Character;
import com.n4v1.pko.server.model.World;
import com.n4v1.pko.server.network.NetHandler;

public class Authentification implements Runnable {
	private Socket socket;
	private PrintWriter out = null;
	private BufferedReader in = null;
	private String login = "zero", pass = null;
	public boolean authentified = false;
	public Thread t2;

	public Authentification(Socket s) {
		socket = s;
	}

	public void run() {
		try {

			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());

			while (!authentified) {
				out.println("Login :");
				out.flush();
				login = in.readLine();

				out.println("Password :");
				out.flush();
				pass = in.readLine();

				if (isValid(login, pass)) {

					out.println("success");
					System.out.println(login + " is online.");
					out.flush();
					authentified = true;
				} else {
					out.println("error");
					out.flush();
				}
				Character c = new Character(login, 20.0f, 22.0f);
				World.getInstance().addCharacter(c);
				Thread netHeandler = new Thread(new NetHandler(socket, c));
				netHeandler.start();
			}
			
		} catch (IOException e) {
			System.err.println(login + " doesn't respond.");
		}
	}

	private static boolean isValid(String login, String pass) {
		boolean allowed = false;
		try {
			Scanner sc = new Scanner(new File("data/logs.txt"));
			while (sc.hasNext()) {
				if (sc.nextLine().equals(login + " " + pass)) {
					allowed = true;
					break;
				}
			}
		} catch (FileNotFoundException e) {
			System.err.println("Login & password file not found.");
		}
		return allowed;

	}
}
